#include "tplate.h"
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;

void load_template_3D(tplate * tp, char *fn)
{
    ifstream tpfile;
    tpfile.open(fn);
    tpfile >> tp->tpsize;
    tp->pos = new int[tp->tpsize * 3];
    for (int i = 0; i < tp->tpsize; ++i)
    {
        tpfile >> tp->pos[i * 3];
        tpfile >> tp->pos[i * 3 + 1];
        tpfile >> tp->pos[i * 3 + 2];
    }
    tpfile.close();
    return;
}

void get_dv_3D(data_event * dv, tplate * tp, target_grid_3D * target,
               int g, int x, int y, int z, int max_dv)
{
    dv->dvsize = 0;
    for (int i = 0; i < tp->tpsize; i++)
    {
        int px = x + tp->pos[i * 3];
        int py = y + tp->pos[i * 3 + 1];
        int pz = z + tp->pos[i * 3 + 2];
        if ((px < 0) || px >= target->length[g])
            continue;
        if ((py < 0) || py >= target->width[g])
            continue;
        if ((pz < 0) || pz >= target->height[g])
            continue;
        int *values = new int[target->NR_cate];
        bool found = false;
        if (g == 0)
        {
            int cur_cate =
                target->hard_data[pz * target->width[0] *
                                  target->length[0] +
                                  py * target->length[0] + px];
            memset(values,0,target->NR_cate*sizeof(int));
            if (cur_cate >= 0)
            {
                values[cur_cate] = 1;
                found = true;
            }
        }
        else
        {
            for (int c = 0; c < target->NR_cate; c++)
            {
                values[c] =
                    target->sample[g].category[(pz * target->width[g] *
                            target->length[g] +
                            py * target->length[g] +
                            px) * target->NR_cate + c];
                if (values[c] > 0)
                    found = true;
            }
        }
        if (found == true)
        {
            int cur_dvpos = dv->dvsize;
            dv->tpos[cur_dvpos] = i;
            dv->pos[cur_dvpos * 3] = (tp->pos[i * 3]);
            dv->pos[cur_dvpos * 3 + 1] = (tp->pos[i * 3 + 1]);
            dv->pos[cur_dvpos * 3 + 2] = (tp->pos[i * 3 + 2]);
            dv->value[cur_dvpos] = values;
            dv->dvsize++;
            if (max_dv <= dv->dvsize)
                break;
        }
    }
    return;
}
